from flask import Blueprint, request, render_template, redirect, url_for
from flask_wtf import FlaskForm
from wtforms.validators import DataRequired, Length
from wtforms.fields import *
from util.dbutil import Base, db
from sqlalchemy import Column, Integer, String, Text, DateTime
import datetime

article = Blueprint('article', __name__, url_prefix='/article')

# bootstrap-flask文档对象
class ArticleForm(FlaskForm):
    title = StringField('标题', validators=[DataRequired(), Length(1, 128)])
    catyegory = SelectField('分类', choices=[('python', 'Python'), ('flask', 'Flask'), ('pytorch', 'Pytorch')])
    content = TextAreaField('内容')
    submit = SubmitField(label='登录')

# 文章表对象
class Article(Base):
    __tablename__ = 'article'  # 数据库表名称， 必须写
    # 主键
    id = Column(Integer, primary_key=True)  
    # 标题
    title = Column(String(128), index=True, nullable=False)  
    # 分类
    catyegory = Column(String(32), index=True, nullable=False)
    # 内容
    content = Column(Text, nullable=False)
    # 创建时间datetime.datetime.now不能加括号，加了括号，以后永远是当前时间
    createtime = Column(DateTime, default=datetime.datetime.now)
    # 更新时间
    updatetime = Column(DateTime, default=datetime.datetime.now)
    # 备注
    extra = Column(Text, nullable=True)
    
# 查询所有文章信息
@article.route('/list')
def articleList():
    articles = db.query(Article).all()
    db.commit()
    titles = [('id', '#'), ('title', '标题'), ('catyegory', '分类'), ('createtime', '创建时间')]
    data = []
    for article in articles:
        data.append({'id': article.id, 'title': article.title, 'catyegory': article.catyegory, 'createtime': article.createtime})
    return render_template('back/article.html', articles=articles, titles=titles, Article=Article, data=data)